<?php
class Userdao extends Controller{
	public static function Register($model){
		if(!$model->validate()){
			return false;
		}
		
		$result=true;
		$check = User::model()->findByAttributes(array('username'=>$model->username));
		if($check != null){
			$model->addError('username', 'Username is valid, please choose other username');
			$result = false;
		}
		$check = User::model()->findByAttributes(array('email'=>$model->email));
		if($check != null){
			$model->addError('email', 'Email is valid, please choose other email');
			$result = false;
		}
		if($result==false){
			return $result;
		}
		$model->salt = Userdao::getRandomNo();
		$model->password = Userdao::endcodePass($model->password,$model->salt);
		$model->idnhom=2;
		$model->trangthai=1;
		$model->save();
		return true;
	}
	
	public static function resetPassword($user){
		$newpass = Userdao::getRandomNo();
		$user->salt = Userdao::getRandomNo();
		$user->password = Userdao::endcodePass($newpass,$user->salt);
		$user->update();
		EmailUtils::sendmailResetPassword($user, $newpass);
	}
	
	public static function getRandomNo(){
		return rand(163245,978534);
	}
	
	public static function login($user, $password){
		if($user == null){
			return false;
		}
		if($user->trangthai == 0){
			return 0;
		}
		
		$pass = crypt($password,$user->salt);
		$pass = md5($pass);
		if($user->password == $pass){
			return true;
		}
		return false;
	}
	
	public static function endcodePass($password,$salt){
		 $pass = crypt($password,$salt);
		return md5($pass);
	}
	
	public static function changepass($model){
		$current = User::model()->findByPK(UserUtils::getUserId());
		if(!Userdao::login($current, $model->oldpassword)){
			$model->addError('oldpassword', 'Nhập mật khẩu không đúng');
			return false;
		}
		$current->salt = Userdao::getRandomNo();
		
		$current->password = Userdao::endcodePass($model->password,$current->salt);

		$current->update();
		return true;
		
	}
}